import {DreamVideo, Movie, VideoInfo} from '@/data/Dream'
import {formatBytes, formatSeconds, getMovieIdObjByVideo} from '@/utils/utils.ts'
import {movieDB} from '@/data/lowdb.ts'

const ffmpeg = require('fluent-ffmpeg')
if (process.env.NODE_ENV !== 'development') {
    // asar打包后路径有所变化
    // ffmpeg.setFfmpegPath(ffmpegPath.path.replace('app.asar', 'app.asar.unpacked'))
    // ffmpeg.setFfprobePath(ffprobePath.path.replace('app.asar', 'app.asar.unpacked'))
} else {
    const ffmpegPath = require('@ffmpeg-installer/ffmpeg')
    const ffprobePath = require('@ffprobe-installer/ffprobe')
    ffmpeg.setFfmpegPath(ffmpegPath.path)
    ffmpeg.setFfprobePath(ffprobePath.path)
}


export async function setVideoOtherInfo(dreamVideo: DreamVideo, dreamVideosRootDir: string, videoFileName: string) {
    const video = dreamVideosRootDir + '/' + videoFileName
    const videoInfo = await getVideoInfo(video)
    if (videoInfo) {
        Object.assign(dreamVideo, videoInfo)
        updateMovieVideoInfo(videoFileName, videoInfo)
    }
}

function updateMovieVideoInfo(videoFileName: string, videoInfo: VideoInfo) {
    const movieIdObj = getMovieIdObjByVideo(videoFileName)
    const movieDBData = movieDB.find(movieIdObj)
    const movie: Movie = movieDBData.value()
    const {
        size,
        duration,
    } = movie
    const newSize = size + videoInfo.size
    const sizeF = formatBytes(newSize)
    const newDuration = Math.round(duration + videoInfo.duration)
    const durationF = formatSeconds(newDuration)
    movieDBData
        .set('size', newSize)
        .set('sizeF', sizeF)
        .set('duration', newDuration)
        .set('durationF', durationF)
        .write()
}

async function getVideoInfo(video: string) {
    return new Promise<VideoInfo>((resolve) => {
        ffmpeg.ffprobe(video, (err: any, data: any) => {
            if (data) {
                resolve({
                    'duration': data.format.duration,
                    'durationF': formatSeconds(data.format.duration),
                    'size': data.format.size,
                    'sizeF': formatBytes(data.format.size),
                })
            } else {
                console.error(err)
                resolve(null)
            }
        })
    })
}
